<template>
  <div class="wrapper" >
    <!-- 主内容区域 -->
    <div class="main-content" style="background-color: #e0e3ff">
      <!-- 内容主体 -->
      <div class="content">
        <h2 class="title">管理员信息</h2>
        <!-- 操作栏 -->
        <div class="operation-bar">
          <el-button type="primary" size="small" @click="handleAdd">
            新增
          </el-button>
          <el-input
              v-model="searchName"
              placeholder="请输入搜索内容"
              class="search-input"
              @keyup.enter="loadTable(1)"
          >
            <template #suffix>
              <i class="el-icon-search"></i>
            </template>
          </el-input>
          <el-button type="primary" @click="loadTable(1)">搜索</el-button>
        </div>

        <!-- 数据表格 -->
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column prop="name" label="姓名"></el-table-column>
          <el-table-column prop="nickName" label="昵称"></el-table-column>
          <el-table-column prop="sex" label="性别"></el-table-column>
          <el-table-column prop="age" label="年龄"></el-table-column>
          <el-table-column prop="phone" label="手机号"></el-table-column>
          <el-table-column prop="email" label="邮箱"></el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{ row }">
              <el-button size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button
                  size="small"
                  type="danger"
                  @click="handleDelete(row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
            v-model:current-page="pagination.pageNum"
            :page-size="pagination.pageSize"
            layout="prev, pager, next"
            :total="pagination.total"
            @current-change="handlePageChange"
        />
      </div>
    </div>

    <el-dialog
        v-model="dialogVisible"
        :title="currentId ? '编辑管理员' : '新增管理员'"
    >
      <el-form
          :model="formData"
          :rules="rules"
          label-width="80px"
          ref="formRef"
      >

        <el-form-item label="姓名" required prop="name">
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input v-model="formData.nickName"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-radio-group v-model="formData.sex">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="formData.age" :min="0"></el-input-number>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email"></el-input>
        </el-form-item>
      </el-form>
      <!-- 自定义页脚 -->
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from "@/utils/request.js";


const router = useRouter()

// 响应式数据
const user = reactive(JSON.parse(localStorage.getItem('user')) || {})
const authority = ref([])
const permission = ref([])
const searchName = ref('')
const tableData = ref([])
const pagination = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})

const dialogVisible = ref(false)
const formData = reactive({
  sex: '男',
  name: '',
  nickName: '',
  age: 0,
  phone: '',
  email: ''
})
const currentId = ref(null)

// 表单引用和验证规则
const formRef = ref(null)
const rules = reactive({
  name: [
    { required: true, message: '姓名不能为空', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度2-10个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '手机号不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '邮箱不能为空', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  age: [
    { required: true, message: '年龄不能为空', trigger: 'blur' },
    { type: 'number', min: 0, max: 150, message: '年龄需在0-150之间', trigger: 'blur' }
  ]
})

// 生命周期钩子
onMounted(async () => {
  await loadTable(1)
  await fetchPermissions()
})

// 方法
const loadTable = async (pageNum = 1) => {
  try {
    const name = searchName.value || 'all'
    const res = await request.get(`/adminInfo/page/${name}`, {
      params: { pageNum }
    })

    if (res.data.code === '0') {
      tableData.value = res.data.data.list
      Object.assign(pagination, {
        pageNum: res.data.data.pageNum,
        pageSize: res.data.data.pageSize,
        total: res.data.data.total
      })
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    ElMessage.error('数据加载失败')
  }
}

const fetchPermissions = async () => {
  try {
    const [permRes, authRes] = await Promise.all([
      request.get('/permission/1'),
      request.get('/authority')
    ])
    console.log("permRes.data.data"+permRes.data.data)
    if (permRes.data.code === '0') permission.value = permRes.data.data
    if (authRes.data.code === '0') authority.value = authRes.data.data
  } catch (error) {
    ElMessage.error('权限加载失败')
  }
}

const handleAdd = () => {
  if (!permission.value.includes(1)) {
    ElMessage.warning('无操作权限')
    return
  }
  Object.assign(formData, {
    sex: '男',
    name: '',
    nickName: '',
    age: null, // 修改为null
    phone: '',
    email: ''
  })
  currentId.value = null
  dialogVisible.value = true
}

const handleEdit = (row) => {
  if (!permission.value.includes(3)) {
    ElMessage.warning('无操作权限')
    return
  }
  Object.assign(formData, {
    ...row,
    age: Number(row.age) // 转换为数字类型
  })
  currentId.value = row.id
  dialogVisible.value = true
}


// handleSubmit方法
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate()
  } catch (error) {
    ElMessage.warning('请正确填写表单')
    return
  }

  try {
    const method = currentId.value ? 'put' : 'post'
    const url = `/adminInfo`
    const res = await request[method](url, formData)
    if (res.data.code === '0') {
      ElMessage.success('操作成功')
      dialogVisible.value = false
      await loadTable(pagination.pageNum)
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const handleDelete = async (id) => {
  if (!permission.value.includes(2)) {
    ElMessage.warning('无操作权限')
    return
  }

  try {
    await ElMessageBox.confirm('确认删除该记录？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const res = await request.delete(`/adminInfo/${id}`)
    if (res.data.code === '0') {
      ElMessage.success('删除成功')
      await loadTable(pagination.pageNum)
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (error) {
    // 取消删除不处理
  }
}

const handlePageChange = (page) => {
  pagination.pageNum = page
  loadTable(page)
}

</script>

<style scoped>
.wrapper {
  display: flex;
  min-height: 100vh;
}

.side-menu {
  width: 200px;
  background: #fff;
  border-right: 1px solid #e6e6e6;
}

.main-content {
  flex: 1;
  background: #f0f2f5;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  height: 60px;
  background: linear-gradient(to bottom, #26a3de, #057db5);
  color: white;
}

.content {
  padding: 20px;
}

.title {
  color: #333;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.operation-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.search-input {
  width: 300px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>